<!DOCTYPE html>
<html>
<head>
    <title>量化信号监控面板</title>
    <meta charset="utf-8">
    <style>
        body { font-family: Arial, sans-serif; margin: 20px; background: #f5f5f5; }
        .container { max-width: 1200px; margin: 0 auto; }
        .status-card { background: white; padding: 20px; margin: 10px 0; border-radius: 8px; box-shadow: 0 2px 4px rgba(0,0,0,0.1); }
        .connected { border-left: 4px solid #28a745; }
        .disconnected { border-left: 4px solid #dc3545; }
        .signal { border: 1px solid #ddd; padding: 15px; margin: 10px 0; border-radius: 5px; background: white; }
        .buy { border-left: 4px solid #28a745; background: #f8fff9; }
        .sell { border-left: 4px solid #dc3545; background: #fff8f8; }
        .pending { background: #fff3cd; }
        .processing { background: #cce7ff; }
        .executed { background: #d4edda; }
        .failed { background: #f8d7da; }
        .stats-grid { display: grid; grid-template-columns: repeat(auto-fit, minmax(200px, 1fr)); gap: 15px; margin: 20px 0; }
        .stat-card { background: white; padding: 15px; border-radius: 8px; text-align: center; box-shadow: 0 2px 4px rgba(0,0,0,0.1); }
        .controls { margin: 20px 0; }
        button { padding: 10px 20px; margin: 5px; border: none; border-radius: 4px; cursor: pointer; }
        .btn-primary { background: #007bff; color: white; }
        .btn-danger { background: #dc3545; color: white; }
        .btn-success { background: #28a745; color: white; }
    </style>
</head>
<body>
    <div class="container">
        <h1>🚀 量化信号监控面板</h1>
        
        <div class="controls">
            <button class="btn-primary" onclick="loadAllData()">刷新数据</button>
            <button class="btn-success" onclick="clearSignals()">清空记录</button>
            <button class="btn-danger" onclick="exportData()">导出数据</button>
        </div>

        <div class="stats-grid">
            <div class="stat-card">
                <h3>待处理信号</h3>
                <div id="pendingCount">0</div>
            </div>
            <div class="stat-card">
                <h3>活跃客户端</h3>
                <div id="clientCount">0</div>
            </div>
            <div class="stat-card">
                <h3>历史信号</h3>
                <div id="historyCount">0</div>
            </div>
            <div class="stat-card">
                <h3>系统状态</h3>
                <div id="systemStatus">运行中</div>
            </div>
        </div>

        <div class="status-card connected">
            <h3>📊 实时信号流</h3>
            <div id="signalList"></div>
        </div>

        <div class="status-card">
            <h3>📋 信号详情</h3>
            <div id="signalDetails">
                <p>选择信号查看详情...</p>
            </div>
        </div>
    </div>

    <script>
        let autoRefresh = true;
        let refreshInterval = 2000; // 2秒刷新

        // 加载所有数据
        async function loadAllData() {
            await loadSystemStatus();
            await loadSignals();
        }

        // 加载系统状态
        async function loadSystemStatus() {
            try {
                const response = await fetch('/api/quant/status');
                const data = await response.json();
                
                document.getElementById('pendingCount').textContent = 
                    Object.values(data.pending_signals).reduce((a, b) => a + b, 0);
                document.getElementById('clientCount').textContent = data.active_clients;
                document.getElementById('historyCount').textContent = data.total_history;
                document.getElementById('systemStatus').textContent = '运行中 ✅';
                
            } catch (error) {
                console.error('获取系统状态失败:', error);
                document.getElementById('systemStatus').textContent = '连接失败 ❌';
            }
        }

        // 加载信号历史
        async function loadSignals() {
            try {
                const response = await fetch('/api/quant/signals?limit=50');
                const data = await response.json();
                
                const signalList = document.getElementById('signalList');
                signalList.innerHTML = '';

                data.signals.reverse().forEach(signal => {
                    const signalElement = document.createElement('div');
                    signalElement.className = `signal ${signal.data.volume > 0 ? 'buy' : 'sell'} ${signal.status}`;
                    signalElement.onclick = () => showSignalDetails(signal);
                    
                    const orderCode = signal.data.orderCode || '未知';
                    const volume = signal.data.volume || 0;
                    const direction = volume > 0 ? '买入' : '卖出';
                    const amount = Math.abs(volume);
                    const time = new Date(signal.timestamp).toLocaleString();

                    signalElement.innerHTML = `
                        <div style="display: flex; justify-content: space-between; align-items: center;">
                            <div>
                                <strong style="font-size: 1.1em;">${direction} ${orderCode}</strong>
                                <br>数量: <strong>${amount}</strong>股
                                <br>时间: ${time}
                            </div>
                            <div style="text-align: right;">
                                <span class="status-badge">${signal.status}</span>
                                <br>Tunnel: ${signal.tunnelId}
                            </div>
                        </div>
                    `;
                    
                    signalList.appendChild(signalElement);
                });

            } catch (error) {
                console.error('获取信号失败:', error);
            }
        }

        // 显示信号详情
        function showSignalDetails(signal) {
            const detailsDiv = document.getElementById('signalDetails');
            detailsDiv.innerHTML = `
                <h4>信号详情</h4>
                <pre>${JSON.stringify(signal, null, 2)}</pre>
            `;
        }

        // 清空信号
        async function clearSignals() {
            if (confirm('确定要清空所有信号记录吗？')) {
                // 这里可以添加清空信号的API调用
                alert('清空功能待实现');
            }
        }

        // 导出数据
        async function exportData() {
            try {
                const response = await fetch('/api/quant/signals?limit=1000');
                const data = await response.json();
                
                const blob = new Blob([JSON.stringify(data, null, 2)], { type: 'application/json' });
                const url = URL.createObjectURL(blob);
                const a = document.createElement('a');
                a.href = url;
                a.download = `quant-signals-${new Date().toISOString().split('T')[0]}.json`;
                a.click();
                URL.revokeObjectURL(url);
                
            } catch (error) {
                console.error('导出失败:', error);
            }
        }

        // 自动刷新
        function startAutoRefresh() {
            setInterval(() => {
                if (autoRefresh) {
                    loadAllData();
                }
            }, refreshInterval);
        }

        // 初始化
        document.addEventListener('DOMContentLoaded', function() {
            loadAllData();
            startAutoRefresh();
        });
    </script>
</body>
</html>